package com.example.administrator.basedemos.netcore;

import com.alibaba.fastjson.JSON;
import com.example.administrator.basedemos.utils.UIUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/27 15:51
 * 描述	      ${将流对象转换指定的类型并传送回主线程}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class JsonDealListener<T> implements IhttpListener {
    /**
     * 我们需要返回值给的类型以及我们要转换的类型
     */
    private Class<T>         mResponseClass;
    private IJsonListener<T> mIJsonListener;

    //Handler mHandler =new Handler(Looper.getMainLooper());

    public JsonDealListener(Class<T> responseClass, IJsonListener<T> IJsonListener) {
        mResponseClass = responseClass;
        mIJsonListener = IJsonListener;
    }

    @Override
    public void onSuccess(InputStream inputStream) {
        String content = getContent(inputStream);
        //将字符串转换成指定的泛型
        final T response ;
         response = JSON.parseObject(content,mResponseClass);
         //通过IjsonListener将转换好的数据传递到主线程
        UIUtils.getMainThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                mIJsonListener.onSuccess(response);
            }
        });
    }


    @Override
    public void onError() {

    }

    private String getContent(InputStream inputStream) {
        String content = null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder sb = new StringBuilder();

            String line = null;

            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }


            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error=" + e.toString());
            } finally {
                try {
                    if (reader != null)
                        reader.close();
                    if (inputStream != null)
                        inputStream.close();
                } catch (IOException e) {
                    System.out.println("Error=" + e.toString());
                    e.printStackTrace();
                }
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error=" + e.toString());
        }
        return content;
    }
}
